import { NextRequest, NextResponse } from 'next/server'
import { projectQueries, userProjectLinkQueries } from '@/lib/database-prisma'
import { getUserFromRequest } from '@/lib/auth-utils'
import type { Project } from '@/types/database'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ projectName: string }> }
) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { projectName } = await params
    const decodedProjectName = decodeURIComponent(projectName)
    
    // 根据项目名称查找项目
    const projects = await projectQueries.getAll.all()
    const project = projects.find(p => p.name === decodedProjectName)
    
    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    // 检查用户是否有权限访问此项目
    const hasAccess = await userProjectLinkQueries.checkUserInProject.get(userInfo.id, project.id)
    if (!hasAccess || hasAccess.count === 0) {
      return NextResponse.json({ error: '您没有访问此项目的权限' }, { status: 403 })
    }
    
    // 返回完整的项目信息，包括ID
    return NextResponse.json(project)
  } catch (error) {
    console.error('根据名称获取项目信息失败:', error)
    return NextResponse.json({ error: '根据名称获取项目信息失败' }, { status: 500 })
  }
} 